<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        /**
         *  localStorage    本地存储，当前会话关闭数据还在
         *  sessionStorage  会话存储，当前浏览器页签关闭、或者浏览器关闭，数据丢失
         * 
         *  注意：存的数据只能是基本数据类型[字符串等]，如果是对象或数组需要转化为json字符串存储
         *  1. 添加值：key - value
         *     localStorage.setItem(key, value)
         *     sessionStorage.setItem(key, value)
         *  2. 获取值：key
         *     localStorage.getItem(key)
         *     sessionStorage.getItem(key)
         *   
         *  3. 删除值：
         *     3-1. 按照key删除
         *     localStorage.removeItem(key)
         *     sessionStorage.removeItem(key)
         *     3-2. 全部删除：
         *     localStorage.clear();
         *     sessionStorage.clear();
         */

        
        // localStorage.setItem('username','atguigu');
        // localStorage.setItem('age', 10);
        // localStorage.setItem('sex', 'boy');
        // console.log(localStorage.getItem('username'));

        // sessionStorage.setItem('age', 10);
        // console.log(sessionStorage.getItem('age'));

        // localStorage.removeItem('username');
        // localStorage.clear();


        // 存储数据类型的问题:

        let user = {
            username:'atguigu',
            age:10
        }

        let todos = [
            {
                id:1,
                title:'吃饭',
                isDone:false
            },
            {
                id:2,
                title:'睡觉',
                isDone:false
            }
        ]
        // 直接向localStorage 和 sessionStorage中存数组和对象，会强转成String在存储，
        // 会丢失原来的数据结构
        // console.log(user.toString(), todos.toString());
        // localStorage.setItem('user', user);
        // localStorage.setItem('todos', todos);

        // let todosList = localStorage.getItem('todos');
        // console.log(todosList, typeof todosList);

        // 存数组和字符串，需要先转化为json格式的字符串，在存储，读取时，需要parse解析还原成原对象或数组

        localStorage.setItem('user2', JSON.stringify(user));
        localStorage.setItem('todos2', JSON.stringify(todos));

        let newUser = JSON.parse(localStorage.getItem('user2'));
        let newTods = JSON.parse(localStorage.getItem('todos2'));
        console.log(newUser, typeof newUser, newUser.username);

        console.log(newTods.length);

        // 3. 如果读取一个不存在的 key 
        console.log(localStorage.getItem('sakdjfkl'));// null
        console.log(JSON.parse(localStorage.getItem('skldjfklasjf')));// null

        // 4. 读取本地存储的信息，如果key不存在 那么，返回一个空数组，如果存在还原成原数组

        let testTodo = JSON.parse(localStorage.getItem('todos2')) || [];
        console.log(testTodo);
    </script>
</body>
</html>